package com.ruixin.parser;

import com.ruixin.annotation.Autowired;
import com.ruixin.annotation.Parser;
import com.ruixin.base.BaseParser;
import com.ruixin.base.exception.BaseException;
import com.ruixin.base.util.BeanUtil;
import com.ruixin.base.util.StringUtil;
import com.ruixin.config.ApplicationContext;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

/**
 * Autowire注解解释
 */
@Parser(annotation = Autowired.class)
public class AutowiredParser extends BaseParser<ApplicationContext> {

    public AutowiredParser(ApplicationContext context, Class<? extends Annotation> type) {
        super(context, type);
    }

    @Override
    public void parseField(Object bean, Field field) throws BaseException {
        super.parseField(bean, field);
        Autowired autowire = BeanUtil.getAnnotation(field, Autowired.class);
        String beanName = autowire.value();
        boolean required = autowire.required();
        if(StringUtil.isBlackOrNull(beanName)){
            beanName = field.getName();
        }
        Object beanObject = this.context.getBean(beanName);
        if(beanObject==null){
            throw new BaseException(bean.getClass().getName()+"."+field.getName()+"中autowire[required=true]但是没找到");
        }
        BeanUtil.invokeField(bean,field,beanObject);
    }
}
